package cn.yunhe.model;

import cn.yunhe.util.ReadResourceUtil;
import com.sun.media.jfxmedia.AudioClip;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.*;
import java.applet.Applet;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 消除区域
 */
public class EliminateBox {
    //注意加static关键字
    private static List<Brand> slot = new ArrayList<>();
    static AudioClip failClip;
    static {
        try {
            String str = System.getProperty("user.dir") +"/music/fail.wav";
            failClip = AudioClip.load(ReadResourceUtil.readAudio(str).toURI());
        } catch (URISyntaxException | IOException e) {
            throw new RuntimeException(e);
        }

    }
    
    

    String str = System.getProperty("user.dir") + "\\music\\fail.wav";
    File file = new File(str);

    //消除方法
    public void addSlot(Brand brand) {
        slot.add(brand);
        //牌的排序，根据牌的名称
        slot.sort(Comparator.comparing(Brand::getName));
        Map<String, List<Brand>> map =
                slot.stream().collect(Collectors.groupingBy(Brand::getName));
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            List<Brand> brands = map.get(key);
            if (brands.size() == 3) {
                deleteBrand(key);
            }
        }
        //调⽤绘制⽅法
        paint();
        //调⽤游戏结束的⽅法
        try {
            gameOver(brand);
        } catch (JavaLayerException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void gameOver(Brand brand) throws JavaLayerException, IOException {
        if (slot.size() == 8){
            failClip.play();
            JOptionPane.showMessageDialog(brand,"Game Over！！");
            System.exit(0);
        }
    }

    /**
     * 迭代器清空集合⽅法
     */
    public void deleteBrand(String name){
        Iterator<Brand> iterator = slot.iterator();
        while (iterator.hasNext()) {
            Brand brand = iterator.next();
            if (brand.getName().equals(name)) {
                brand.getParent().remove(brand);//ui界⾯删除
                iterator.remove();//数据结构删除
            }
        }
    }

    //绘制消除框
    public void paint() {
        for (int i = 0; i < slot.size(); i++) {
            Brand brand = slot.get(i);
            int x = i * brand.getWidth() + 10;
            brand.setBounds(x, 600, 50, 50);
        }
    }
}